<template>
  <view class="work-container">
    <!-- 轮播图 -->
    <uni-swiper-dot class="uni-swiper-dot-box" :info="data" :current="current" field="content">
      <swiper class="swiper-box" :current="swiperDotIndex" @change="changeSwiper">
        <swiper-item v-for="(item, index) in data" :key="index">
          <view class="swiper-item" @click="clickBannerItem(item)">
            <image :src="item.image" mode="aspectFill" :draggable="false" />
          </view>
        </swiper-item>
      </swiper>
    </uni-swiper-dot>

    <!-- 系统管理 -->
    <uni-section title="系统管理" type="line"></uni-section>

    <!-- 使用 uni-grid 均分3列 -->
    <uni-grid :column="3" :showBorder="false">
      <uni-grid-item v-for="(item, index) in gridItems" :key="index">
        <view class="grid-item-box" @click.stop="handleGridClick(item)">
          <uni-icons :type="item.icon" size="30"></uni-icons>
          <text class="text">{{ item.text }}</text>
          <!-- 如果是个人工单且有数量则显示徽标 -->
          <view v-if="item.showBadge && personalCount > 0" class="badge">{{ personalCount }}</view>
        </view>
      </uni-grid-item>
    </uni-grid>
  </view>
</template>

<script>
const db = uniCloud.database()

export default {
 data() {
   return {
     current: 0,
     swiperDotIndex: 0,
     personalCount: 0,
     isAdmin: false, // 是否为管理员
     gridItems: [], // 动态宫格数据
     data: [
       { image: 'https://zzx1028.oss-cn-beijing.aliyuncs.com/38f605d1-6555-4c74-98bd-4bf8aa1ea3ef.jpg' },
       { image: 'https://zzx1028.oss-cn-beijing.aliyuncs.com/4e07eb1a-f35e-4394-bb92-8d0d8d59783f.jpg' },
       { image: 'https://zzx1028.oss-cn-beijing.aliyuncs.com/6ff26e55-4f62-462d-841d-46615166b173.jpg' }
     ],
     lastClick: 0
   }
 },
 async onLoad() {
   // 假设你在登录时已经把 user 对象缓存到了本地存储中
   const userInfo = uni.getStorageSync('userInfo') // 获取完整的用户信息对象
 
   if (userInfo && userInfo.admin !== undefined) {
     this.isAdmin = userInfo.admin
     this.initGridItems()
   } else {
     uni.showToast({ title: '无法识别用户身份', icon: 'none' })
   }
 
   await this.loadPersonalCount()
 },
  methods: {
    // 加载个人工单数量
    async loadPersonalCount() {
      try {
        const res = await db.collection('orders')
          .where({
            creatorId: uni.getStorageSync('userId'),
            status: '进行中'
          })
          .count()
        this.personalCount = res.result.total
      } catch (e) {
        console.error('获取数量失败:', e)
      }
    },
	 initGridItems() {
	    if (this.isAdmin) {
	      this.gridItems = [
	        { index: 0, text: '全部工单', icon: 'staff-filled', route: '/pages/work/allOrder/allOrder' },
	        { index: 1, text: '订单列表', icon: 'wallet-filled', route: '/pages/order/index' }
	      ]
	    } else {
	      this.gridItems = [
	        { index: 0, text: '个人工单', icon: 'person-filled', route: '/pages/work/personalOrder/personalOrder', showBadge: true }
	      ]
	    }
	  },

    // 处理宫格点击（带防抖）
  handleGridClick(item) {
    const now = Date.now()
    if (now - this.lastClick < 300) return
    this.lastClick = now
  
    let url = item.route
  
    // 如果是个人工单，并且有 empId，则携带参数
    if (item.text === '个人工单') {
      const empId = uni.getStorageSync('empId') || uni.getStorageSync('userInfo')?.empId
      if (empId) {
        url += `?empId=${empId}`
      } else {
        uni.showToast({ title: '此员工无工单', icon: 'none' })
        return
      }
    }
  
    uni.navigateTo({ url })
  },

    clickBannerItem(item) {
      console.info('点击轮播图:', item)
    },
    
    changeSwiper(e) {
      this.current = e.detail.current
    },
    
    // 兼容旧版事件
    changeGrid(e) {
      this.handleGridClick(e.detail.index)
    },
	navigateToOrderList() {
    console.log('点击了订单列表'); // 应该能看到输出
    uni.navigateTo({
      url: '/pages/order/index'
    });
  }
  }
}
</script>

<style lang="scss" scoped>
.work-container {
  padding-bottom: 30rpx;
}

.grid-body {
  padding: 20rpx;
}

.grid-item-box {
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
  transition: transform 0.2s;

  &:active {
    transform: scale(0.95);
  }
}

.badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  min-width: 30rpx;
  height: 30rpx;
  line-height: 30rpx;
  background: #f56c6c;
  color: white;
  border-radius: 15rpx;
  font-size: 20rpx;
  text-align: center;
  padding: 0 8rpx;
}

.swiper-box {
  height: 300rpx;
}

.swiper-item {
  height: 300rpx;
  overflow: hidden;
  
  image {
    width: 100%;
    height: 100%;
  }
}

@media (min-width: 768px) {
  .uni-swiper-dot-box {
    max-width: 750px;
    margin: 0 auto;
  }
}
</style>